package com.uls.web.controller.hj;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.uls.common.core.domain.entity.SysRole;
import com.uls.common.core.domain.entity.SysUser;
import com.uls.hj.domain.HjMessages;
import com.uls.hj.domain.HjVenueSchedules;
import com.uls.hj.domain.HjVenues;
import com.uls.hj.service.IHjMessagesService;
import com.uls.hj.service.IHjVenueSchedulesService;
import com.uls.hj.service.IHjVenuesService;
import com.uls.system.service.ISysRoleService;
import com.uls.system.service.ISysUserService;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.uls.common.annotation.Log;
import com.uls.common.core.controller.BaseController;
import com.uls.common.core.domain.AjaxResult;
import com.uls.common.enums.BusinessType;
import com.uls.hj.domain.HjBookings;
import com.uls.hj.service.IHjBookingsService;
import com.uls.common.utils.poi.ExcelUtil;
import com.uls.common.core.page.TableDataInfo;

/**
 * 预订Controller
 * 
 * @author hj
 * @date 2024-11-09
 */
@RestController
@RequestMapping("/hj/bookings")
public class HjBookingsController extends BaseController
{
    @Autowired
    private IHjBookingsService hjBookingsService;

    @Autowired
    private IHjVenuesService hjVenuesService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private IHjVenueSchedulesService hjVenueSchedulesService;

    @Autowired
    private IHjMessagesService hjMessagesService;

    /**
     * 查询预订列表
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:list')")
    @GetMapping("/list")
    @Transactional
    public TableDataInfo list(HjBookings hjBookings)
    {
        hjBookings.setDelFlag(0);

        BaseController baseController = new BaseController();
        Long userId = baseController.getUserId();
        String userName = baseController.getUsername();
        String role = sysUserService.selectUserRoleGroup(userName);
        System.out.println(role);

        if (!role.equals("超级管理员")){
            hjBookings.setUserId(userId);
        }

        startPage();//要放到需要分页的查询语句前
        List<HjBookings> list = hjBookingsService.selectHjBookingsList(hjBookings);

        for (HjBookings hjBookings1: list){
            Long venueId = hjBookings1.getVenueId();
            HjVenues hjVenues = hjVenuesService.selectHjVenuesByVenueId(venueId);
            if (hjVenues != null){
                String venueName = hjVenues.getVenueName();
                hjBookings1.setVenueName(venueName);
            }

            SysUser sysUser = sysUserService.selectUserById(hjBookings1.getUserId());
            if (sysUser != null){
                hjBookings1.setBookingBy(sysUser.getNickName());
                hjBookings1.setBookingAccount(sysUser.getUserName());
                hjBookings1.setPhonenumber(sysUser.getPhonenumber());
            }
        }

        return getDataTable(list);
    }

    /**
     * 导出预订列表
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:export')")
    @Log(title = "预订", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HjBookings hjBookings)
    {
        List<HjBookings> list = hjBookingsService.selectHjBookingsList(hjBookings);
        ExcelUtil<HjBookings> util = new ExcelUtil<HjBookings>(HjBookings.class);
        util.exportExcel(response, list, "预订数据");
    }

    /**
     * 获取预订详细信息
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:query')")
    @GetMapping(value = "/{bookingId}")
    public AjaxResult getInfo(@PathVariable("bookingId") Long bookingId)
    {
        return success(hjBookingsService.selectHjBookingsByBookingId(bookingId));
    }

    /**
     * 新增预订
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:add')")
    @Log(title = "预订", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody HjBookings hjBookings)
    {
        //获取当前登陆用户id
        BaseController baseController = new BaseController();
        Long userId = baseController.getUserId();
        hjBookings.setUserId(userId);

        Long venueId = hjBookings.getVenueId();
        String bookingTime = hjBookings.getBookingTime();

        String bookingTimeString = "";
        if (bookingTime.equals("0")){
            bookingTimeString = "8:00~11:00";
        }else if (bookingTime.equals("1")){
            bookingTimeString = "13:00~16:00";
        }else if (bookingTime.equals("2")){
            bookingTimeString = "16:00~19:00";
        }

        Date currentDate = new Date();
        System.out.println(currentDate);
        //当前日期字符串，格式：yyyy-MM-dd
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //String today = dateFormat.format(currentDate);
        //System.out.println(today);
        Date bookingDate = hjBookings.getBookingDate();
        System.out.println(bookingDate);
        String bookingDateString = dateFormat.format(bookingDate);
        //System.out.println(bookingDateString);

        // 比较日期
        if (!bookingDate.after(currentDate)) {
            // 预约日期在当前日期之前，返回错误响应
            return AjaxResult.error("预约日期必须在当前日期之后!");
        }else {
            HjVenueSchedules venueSchedules = new HjVenueSchedules();
            venueSchedules.setScheduleDate(bookingDate);
            venueSchedules.setVenueId(venueId);
            List<HjVenueSchedules> list = hjVenueSchedulesService.selectHjVenueSchedulesList(venueSchedules);
            if (list != null){
                for (HjVenueSchedules venueSchedules1: list){
                    if (bookingTime.equals(venueSchedules1.getUseTime())){
                        return AjaxResult.error("所选时段已被预约!");
                    }
                }
            }
            HjMessages messages = new HjMessages();
            messages.setReceiverId(hjBookings.getUserId());
            messages.setMessageType(0L);
            HjVenues venues = hjVenuesService.selectHjVenuesByVenueId(venueId);
            messages.setMessageContent("请注意提交预约！！  您已添加一条预约 [" + venues.getVenueName() +
                    "," + bookingDateString + "," + bookingTimeString + "] 的信息，请确认无误后尽快提交！！");
            hjMessagesService.insertHjMessages(messages);

        }

        return toAjax(hjBookingsService.insertHjBookings(hjBookings));
    }

    /**
     * 修改预订
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:edit')")
    @Log(title = "预订", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody HjBookings hjBookings)
    {
        Long venueId = hjBookings.getVenueId();
        String bookingTime = hjBookings.getBookingTime();
        Date currentDate = new Date();
        Date bookingDate = hjBookings.getBookingDate();
        if (!bookingDate.after(currentDate)) {
            // 预约日期在当前日期之前，返回错误响应
            return AjaxResult.error("预约日期必须在当前日期之后!");
        }else{
            HjVenueSchedules venueSchedules = new HjVenueSchedules();
            venueSchedules.setScheduleDate(bookingDate);
            venueSchedules.setVenueId(venueId);
            List<HjVenueSchedules> list = hjVenueSchedulesService.selectHjVenueSchedulesList(venueSchedules);
            if (list != null){
                for (HjVenueSchedules venueSchedules1: list){
                    if (bookingTime.equals(venueSchedules1.getUseTime())){
                        return AjaxResult.error("所选时段已被预约!");
                    }
                }
            }
        }


        return toAjax(hjBookingsService.updateHjBookings(hjBookings));
    }

    /**
     * 删除预订
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:remove')")
    @Log(title = "预订", businessType = BusinessType.DELETE)
	@DeleteMapping("/{bookingIds}")
    public AjaxResult remove(@PathVariable Long[] bookingIds)
    {
        //return toAjax(hjBookingsService.deleteHjBookingsByBookingIds(bookingIds));

        Integer delFlag = 1;
        Map<String, Object> params = new HashMap<>();
        params.put("delFlag", delFlag);

        if (bookingIds.length == 1) {
            Long bookingId = bookingIds[0];
            params.put("bookingId", bookingId);
            return toAjax(hjBookingsService.updateHjBookingsByBookingId(params));
        }
        params.put("bookingIds", bookingIds);
        return toAjax(hjBookingsService.updateHjBookingsByBookingIds(params));

    }


    /**
     * 提交预约
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:bookingSubmit')")
    @Log(title = "预约信息", businessType = BusinessType.EXPORT)
    @GetMapping("/submitBooking/{bookingId}")
    @Transactional
    public AjaxResult submitBooking(@PathVariable Long bookingId)
    {
        HjBookings hjBookings = hjBookingsService.selectHjBookingsByBookingId(bookingId);

        String bookingTime = hjBookings.getBookingTime();
        String bookingTimeString = "";
        if (bookingTime.equals("0")){
            bookingTimeString = "8:00~11:00";
        }else if (bookingTime.equals("1")){
            bookingTimeString = "13:00~16:00";
        }else if (bookingTime.equals("2")){
            bookingTimeString = "16:00~19:00";
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String bookingDateString = dateFormat.format(hjBookings.getBookingDate());

        HjMessages messages = new HjMessages();
        messages.setReceiverId(hjBookings.getUserId());
        messages.setMessageType(0L);
        HjVenues venues = hjVenuesService.selectHjVenuesByVenueId(hjBookings.getVenueId());
        messages.setMessageContent("您的预约提交成功！！  您的预约信息： [" + venues.getVenueName() +
                "," + bookingDateString + "," + bookingTimeString + "] ，已成功提交！！");
        hjMessagesService.insertHjMessages(messages);

        return  toAjax(hjBookingsService.submit(bookingId,getUserId()));
    }

    ////审批相关

    /**
     * 查询未审批的预约信息列表
     */

    @PreAuthorize("@ss.hasPermi('hj:bookings:listNo')")
    @GetMapping("/listNo")
    public TableDataInfo listNo(HjBookings booking)
    {
        startPage();
        booking.setDelFlag(0);
        // List<SysStudent> list = sysStudentService.noFinishTask(getUserId(),"myStudentProcess");//关联工作流没有带条件查询
        List<HjBookings> list = hjBookingsService.noFinishTask(getUserId(),"bookingProcess",booking);//关联工作流带条件查询

        for (HjBookings hjBookings1: list){
            Long venueId = hjBookings1.getVenueId();
            HjVenues hjVenues = hjVenuesService.selectHjVenuesByVenueId(venueId);
            if (hjVenues != null){
                String venueName = hjVenues.getVenueName();
                hjBookings1.setVenueName(venueName);
            }

            SysUser sysUser = sysUserService.selectUserById(hjBookings1.getUserId());
            if (sysUser != null){
                hjBookings1.setBookingBy(sysUser.getNickName());
                hjBookings1.setBookingAccount(sysUser.getUserName());
                hjBookings1.setPhonenumber(sysUser.getPhonenumber());
            }
        }

        return getDataTable(list);


    }

    /**
     * 获取预约信息详细信息
     */
    @GetMapping(value = "/getBookingComment/{bookingId}")
    public AjaxResult getInfoComment(@PathVariable("bookingId") Long bookingId)
    {
        HjBookings booking=hjBookingsService.selectHjBookingsByBookingId(bookingId);

        booking.setTaskCommentVoList(hjBookingsService.getTaskCommentList(booking.getFlowInstantId()));  //找出前面审批人的审批信息

        return success(booking);
    }

    /**
     * 完成审批
     */
    @PreAuthorize("@ss.hasPermi('hj:bookings:editnoapprove')")
    @Log(title = "完成审批", businessType = BusinessType.EXPORT)
    @PostMapping("/editnoapprove")
    public AjaxResult editSaveNoAuthData(@RequestBody HjBookings booking)
    {
        Integer agree = booking.getAgree();
        if (agree == 1){
            HjVenueSchedules venueSchedules = new HjVenueSchedules();
            venueSchedules.setScheduleDate(booking.getBookingDate());
            venueSchedules.setVenueId(booking.getVenueId());
            List<HjVenueSchedules> list = hjVenueSchedulesService.selectHjVenueSchedulesList(venueSchedules);
            if (list != null){
                for (HjVenueSchedules venueSchedules1: list){
                    String bookingTime = booking.getBookingTime();
                    if (bookingTime.equals(venueSchedules1.getUseTime())){
                        return AjaxResult.error("该时段已被分配!");
                    }
                }
            }
        }

        hjBookingsService.completeTask(booking.getFlowInstantId(),booking.getAgree(),getUserId(),booking.getComment(),booking.getBookingId());
        return  toAjax(200);
    }

    /**
     * 查询完成审批的学生信息列表
     */

    @PreAuthorize("@ss.hasPermi('hj:bookings:listFinished')")
    @GetMapping("/listFinished")
    public TableDataInfo listFinished(HjBookings bookings)
    {
        startPage();
        bookings.setDelFlag(0);
        //List<SysStudent> list = sysStudentService.finishTask(getUserId(),"myStudentProcess");//关联工作流没有带条件查询
        List<HjBookings> list = hjBookingsService.finishTask(getUserId(),"bookingProcess", bookings);//关联工作流带条件查询

        for (HjBookings hjBookings1: list){
            Long venueId = hjBookings1.getVenueId();
            HjVenues hjVenues = hjVenuesService.selectHjVenuesByVenueId(venueId);
            if (hjVenues != null){
                String venueName = hjVenues.getVenueName();
                hjBookings1.setVenueName(venueName);
            }

            SysUser sysUser = sysUserService.selectUserById(hjBookings1.getUserId());
            if (sysUser != null){
                hjBookings1.setBookingBy(sysUser.getNickName());
                hjBookings1.setBookingAccount(sysUser.getUserName());
                hjBookings1.setPhonenumber(sysUser.getPhonenumber());
            }
        }

        return getDataTable(list);
    }



}
